
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

var DEF_PI = 3.14159265359; // PI
var DEF_2PI = 6.28318530712; // 2*PI
var DEF_PI180 = 0.01745329252; // PI/180.0
var DEF_R = 6370693.5; // radius of earth


function getDistance(lat1, lng1, lat2, lng2) {
  var ew1, ns1, ew2, ns2;
  var dx, dy, dew;
  var distance;
  // 角度转换为弧度
  ew1 = lng1 * DEF_PI180;
  ns1 = lat1 * DEF_PI180;
  ew2 = lng2 * DEF_PI180;
  ns2 = lat2 * DEF_PI180;
  // 经度差
  dew = ew1 - ew2;
  // 若跨东经和西经180 度，进行调整
  if (dew > DEF_PI)
    dew = DEF_2PI - dew;
  else if (dew < -DEF_PI)
    dew = DEF_2PI + dew;
  dx = DEF_R * Math.cos(ns1) * dew; // 东西方向长度(在纬度圈上的投影长度)
  dy = DEF_R * (ns1 - ns2); // 南北方向长度(在经度圈上的投影长度)
  // 勾股定理求斜边长
  distance = Math.sqrt(dx * dx + dy * dy).toFixed(0);
	distance = parseInt(distance);
  return distance;
}

function formatDistance(distance) {
  var str = "";
  if (distance < 1000) {
    str = distance + "m";
  } else {
    distance = distance / 1000;
    str = distance.toFixed(2) + "km";
  }
  return str;
}

function sortList(list) {
	for (let p = 1; p < list.length; p++) {
    for (let q = p - 1; q >= 0; p--, q--) {
      if (list[q].distance > list[p].distance) {
        [list[p], list[q]] = [list[q], list[p]];
      } else {
        break;
      }
    }
  }
	return list;
}

function getDistanceStr(lat1, lng1, lat2, lng2) {
  var str = "";
  var distance = getDistance(lat1, lng1, lat2, lng2);
  if (distance < 1000) {
    str = distance + "m";
  } else {
    distance = distance/1000;
    str = distance.toFixed(2) + "km";
  }
  return str;
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function isBlank(str) {
  return str == null || str == "";
}

function notBlank(str) {
  return !isBlank(str);
}


function showError(msg) {
  wx.showToast({
    title:msg,
    icon: 'none'
  });
}

module.exports = {
  formatTime: formatTime,
  showError: showError,
  isBlank: isBlank,
  notBlank: notBlank,
  getDistance: getDistance,
  getDistanceStr: getDistanceStr,
  formatDistance: formatDistance,
	sortList: sortList
}
